const Imap = require('imap');
const { MailParser } =require('mailparser');
const fs = require('fs');
const path = require('path');

const imap = new Imap({
    user: '1677214021@qq.com',
    password: 'rdwftldzcxukdefj',
    host: 'imap.qq.com',
    port: 993,
    tls: true
});

imap.once('ready', () => {
    imap.openBox('INBOX', true, (err) => {
        // ['SEEN'] - 查询已读的邮件
        // ['SINCE', '某个日期'] - 查询这个日期以来的邮件
        imap.search([['SEEN'], ['SINCE', new Date('2023-05-01 19:00:00')]], (err, results) => {
            if (!err) {
                // results(邮件所属ID)
                handleResults(results)
            } else {
                throw err;
            }
        });
    });
});

imap.connect();

function handleResults(results) {
    imap.fetch(results, { 
        bodies: '',
    }).on('message', (msg) => {
        const mailparser = new MailParser();

        // 解析ID得出的结果
        msg.on('body', (stream) => {
            const info = {};
            // 使用mailparser包解析邮件内容
            stream.pipe(mailparser);

            // 存储邮件头部内容
            mailparser.on("headers", (headers) => {
                info.theme = headers.get('subject');
                info.form = headers.get('from').value[0].address;
                info.mailName = headers.get('from').value[0].name;
                info.to = headers.get('to').value[0].address;
                info.datatime = headers.get('date').toLocaleString();
            });

            // 存储邮件本体内容
            mailparser.on("data", (data) => {
                if (data.type === 'text') {
                    info.html = data.html;
                    info.text = data.text;

                    // 存在HTML内容, 则保存到本地mails文件夹中
                    const filePath = path.join(__dirname, 'email/mails', info.theme + '.html');
                    fs.writeFileSync(filePath, info.html || info.text)

                    console.log(info);
                }
                if (data.type === 'attachment') {
                    // 存在附件, 则保存到本地files文件夹中
                    const filePath = path.join(__dirname, 'email/files', data.filename);
                    const ws = fs.createWriteStream(filePath);
                    data.content.pipe(ws);
                }
            });
        });
    });
}
